package com.customer.controller;

import com.customer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    // eureka客户端，可以获取eureka中的服务信息
    @Autowired
    private EurekaDiscoveryClient discoveryClient;

    @RequestMapping("/findUserAll")
    public List<User> findUserAll(){
        List<User> users = (List<User>)this.restTemplate.getForObject("http://localhost:9000/findUserAll", List.class);
        return users;
    }

    /**
     * 手动式调用
     * @return
     */
    @RequestMapping("/eurekaTest")
    public List<User> eurekaTest(){
        // 根据服务名获取所有服务实例，有可能是集群所以是service实例
        List<ServiceInstance> instances = this.discoveryClient.getInstances("service-provider");
        // 因为现在只有一个服务，所以获取第一个
        ServiceInstance serviceInstance = instances.get(0);
        // 获取ip和端口信息，拼接成服务地址
        String baseUrl = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/findUserAll";
        List<User> list = this.restTemplate.getForObject(baseUrl,List.class);
        return list;
    }

    /**
     * 通过服务名调用
     * @return
     */
    @RequestMapping("/eurekaServiceName")
    public List<User> eurekaByServiceNameTest(){
        // 通过服务名调用
        String baseUrl = "http://service-provider/findUserAll";
        List<User> list = this.restTemplate.getForObject(baseUrl,List.class);
        return list;
    }
}
